package com.pospi.xstore.ui.bh;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.maning.library.MClearEditText;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.mylhyl.circledialog.view.listener.OnCreateBodyViewListener;
import com.pospi.xstore.R;
import com.pospi.xstore.dto.StoreBeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.diaob.BillBeen;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.SaveOrderInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import lib.kingja.switchbutton.SwitchMultiButton;

/*
*调拨收货
 */

public class SupAutoListActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.tv_bt_start)
    TextView tv_bt_start;
    @Bind(R.id.tv_md)
    TextView tv_md;
    @Bind(R.id.tv_out_md)
    TextView tv_out_md;

    private List<StoreBeen> storeBeens;
    private List<String> strings = new ArrayList<>();
    private List<BhGoodsBeen> beens = new ArrayList<>();
    private String count;
    private String je;
    private MyAdapter adapter;
    private MClearEditText sl;

    private String inMark;
    private String outMark;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_bh_list);
        ButterKnife.bind(this);
        setTitle("补货建议单");
        init();
        downStore();
    }



    private void init() {
        tv_md.setOnClickListener(this);
        tv_bt_start.setOnClickListener(this);
        tv_out_md.setOnClickListener(this);
        ListView bill_list = (ListView) findViewById(R.id.list_bill);
        adapter = new MyAdapter();
        bill_list.setAdapter(adapter);
        bill_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final BhGoodsBeen goodsBeen = beens.get(i);
                new CircleDialog.Builder(SupAutoListActivity.this)
                        .setBodyView(R.layout.dialog_layout_bh, new OnCreateBodyViewListener() {
                            @Override
                            public void onCreateBodyView(View view) {
                                sl = view.findViewById(R.id.et_goods_num);
                                TextView kc = view.findViewById(R.id.tv_kcsl);
                                kc.setText(goodsBeen.getKcsl());
                            }
                        })
                        .setPositive("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (NumberCheck(sl.getText().toString().trim())) {
                                    goodsBeen.setSuj(String.valueOf(Double.parseDouble(sl.getText().toString().trim())));
                                }
                                adapter.notifyDataSetChanged();
                            }
                        })
                        .setCancelable(false)
                        .setTitle(goodsBeen.getName())
                        .setNegative("取消", null)
                        .show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_md:
                storeBeens = SaveOrderInfo.changeStoreToList(SPHelper.getInstance().getString(Constant.STORE_LIST));
                strings.clear();
                for (StoreBeen been : storeBeens) {
                    strings.add(been.getName());
                }
                creatDialog(strings);
                break;
            case R.id.tv_bt_start:
                if (beens.size() == 0) {
                    Toast.makeText(this, "商品数据为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (tv_out_md.getText().toString().isEmpty()) {
                    Toast.makeText(this, "请选择配送门店", Toast.LENGTH_SHORT).show();
                    return;
                }
                startSc();
                break;
            case R.id.tv_out_md:
                storeBeens = SaveOrderInfo.changeStoreToList(SPHelper.getInstance().getString(Constant.STORE_LIST));
                strings.clear();
                for (StoreBeen been : storeBeens) {
                    strings.add(been.getName());
                }
                creatDialog2(strings);
                break;
        }
    }

    private class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return beens.size();
        }

        @Override
        public Object getItem(int i) {
            return beens.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder ;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(SupAutoListActivity.this).inflate(R.layout.bh_list_item, null);
                holder.name = view.findViewById(R.id.name);
                holder.code = view.findViewById(R.id.code);
                holder.kcsl = view.findViewById(R.id.kcsl);
                holder.min_sl = view.findViewById(R.id.min_sl);
                holder.max_sl = view.findViewById(R.id.max_sl);
                holder.bhsl = view.findViewById(R.id.bhsl);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            BhGoodsBeen been = beens.get(i);
            holder.name.setText(been.getName());
            holder.code.setText(been.getBarcode());
            holder.kcsl.setText("库存数量："+been.getKcsl());
            holder.min_sl.setText("最小库存："+been.getMin());
            holder.max_sl.setText("最大库存："+been.getMax());
            holder.bhsl.setText(been.getSuj());
            return view;
        }
        class Holder{
            TextView name;
            TextView code;
            TextView kcsl;
            TextView min_sl;
            TextView max_sl;
            TextView bhsl;

        }
    }
    private void searchBill(String id) {
        beens.clear();
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.replenishment");
        params.put("type", "201");
        params.put("table", "xb_base_safestorck");
        params.put("fun", "sujGoodsStock");

//        params.put("page", "");
//        params.put("limit", "");


        JSONObject object = new JSONObject();
        try {
            object.put("marketid", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    Log.i("login", jsonObject.getString("errMsg"));
                    String code = jsonObject.getString("errCode");
                    if (code.equals("100")) {
                        List<BhGoodsBeen> list = new Gson().fromJson(result.toString(),
                                new TypeToken<List<BhGoodsBeen>>() {
                                }.getType());
                        beens.addAll(list);
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 2;
                        message.obj = jsonObject.getString("errMsg");
                        handler.sendMessage(message);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = 2;
                    message.obj = "解析异常";
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    adapter.notifyDataSetChanged();
                    break;
                case 2:
                    adapter.notifyDataSetChanged();
                    close();
                    Toast.makeText(SupAutoListActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    close();
                    new CircleDialog.Builder()
                            .setTitle("提示")
                            .setText("生成补货单成功!")
                            .setPositive("确定", null)
                            .show(getSupportFragmentManager());
                    break;
                case 4:
                    close();
                    new CircleDialog.Builder()
                            .setTitle("提示")
                            .setText("生成补货单失败："+msg.obj)
                            .setPositive("确定", null)
                            .show(getSupportFragmentManager());
                    break;
            }

        }
    };


    //下载门店
    private void downStore() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    SPHelper.getInstance().putString(Constant.STORE_LIST, result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }

    private void creatDialog(List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //门店
                        tv_md.setText(storeBeens.get(i).getName());
                        searchBill(storeBeens.get(i).getId());
                        inMark = storeBeens.get(i).getId();
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }
    private void creatDialog2(List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //门店
                        tv_out_md.setText(storeBeens.get(i).getName());
                        outMark = storeBeens.get(i).getId();
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }
    private void startSc() {
        showDialog();
        beens.clear();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.replenishment");
        params.put("type", "201");
        params.put("table", "xb_base_safestorck");
        params.put("fun", "create");
        params.put("outmarket", outMark);
        params.put("inmarket", inMark);

        JSONArray array = new JSONArray();

        for (BhGoodsBeen been : beens) {
            JSONObject object = new JSONObject();
            try {
                object.put("marketid", inMark);
                object.put("goodsid", been.getGoodsid());
                object.put("sl", been.getSuj());
                array.put(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        params.put("pds", array.toString());
        Log.i("login",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    Log.i("login", jsonObject.getString("errMsg"));
                    String code = jsonObject.getString("errCode");
                    if (code.equals("100")) {
                        Message message = Message.obtain();
                        message.what = 3;
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 4;
                        message.obj = jsonObject.getString("errMsg");
                        handler.sendMessage(message);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = 4;
                    message.obj = "解析异常";
                    handler.sendMessage(message);
                }


            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });
    }
}
